package com.heima.tanhua.filter;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

@Order(-1)
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    @Autowired
    private Config config;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求头信息
        MultiValueMap<String, String> params = exchange.getRequest().getHeaders();

        List<String> whiteList = config.getWhite();
        // whiteList.add("/user/login");
        log.info("{}",whiteList);

        String url = exchange.getRequest().getPath().toString();
        if (whiteList.contains(url)) {
            System.out.println("放行了");
            return chain.filter(exchange);
        }

        // 2.获取authorization参数
        String token = params.getFirst("authorization");

        boolean verify = JWTUtil.verify(token, "tanhua".getBytes());
        if (!verify) {
            // 阻止
            return getVoidMono(exchange);
        }
        // 4.获取用户信息
        JWT jwt = JWTUtil.parseToken(token);
        // 获取载荷
        JWTPayload payload = jwt.getPayload();
        if (payload == null) {

            return getVoidMono(exchange);
        }
        Object id = payload.getClaim("id");
        if (id == null) {
            return getVoidMono(exchange);
        }

        // 把解析到的用户信息，存放到请求头上
        ServerHttpRequest requestNew = exchange.getRequest().mutate().headers(new Consumer<HttpHeaders>() {
            @Override
            public void accept(HttpHeaders httpHeaders) {
                httpHeaders.add("id", id.toString());
            }
        }).build();
        exchange.mutate().request(requestNew).build();

        System.out.println("放行成功");
        return chain.filter(exchange);


    }

    private Mono<Void> getVoidMono(ServerWebExchange exchange) {
        // 4.1.禁止访问，设置状态码
        // 1。获取响应结构，设置状态
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        // 4.2.结束处理
        return exchange.getResponse().setComplete();
    }
}